<template>
  <BasicModal v-bind="config" :title="currTitle" v-model:open="open" wrapClassName="loginSelectModal">
    <a-form ref="formRef" v-bind="layout" :colon="false" class="loginSelectForm">
      <a-form-item v-if="isMultiTenant" :validate-status="validate_status">
        <template #label>
          <a-tooltip placement="topLeft">
            <template #title>
              <span>请选择租户</span>
            </template>
            <a-avatar style="background-color: #87d068" :size="30"> 租户 </a-avatar>
          </a-tooltip>
        </template>
        <a-tree-select v-model:value="tenantSelected" @change="heandleTenantChange" showSearch placeholder="请选择租户"
          :tree-data="tenantList" :dropdown-style="{ maxHeight: '600px', overflow: 'auto' }"
          v-model:treeExpandedKeys="treeExpandedKeys"
          tree-default-expand-all
          tree-node-filter-prop="label"
          popupClassName="select-tenant-item"
          :class="{ 'valid-error': validate_status == 'error' }"
        >
          <template #title="data">
            <div class="select-tenant-item">
              <span class="title">{{ data.label }} &nbsp;</span>
              <span class="tenant-item-tag">
                <a-tag v-if="data.tenantTypeName" color="green">{{ data.tenantTypeName }}</a-tag>
              </span>
            </div>
          </template>
        </a-tree-select>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button @click="handleSubmit" type="primary">确认</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, unref, onMounted } from 'vue';
import { BasicModal } from '/@/components/Modal';
import { listTenantTree } from '/@/api/sys/user';
import { useMessage } from '/@/hooks/web/useMessage';
import { useUserStore } from '/@/store/modules/user';
import { useRouter } from 'vue-router'
import { resetRouter } from '/@/router';
import { Icon } from '/@/components/Icon';
import { flatten } from '/@/utils/helper/treeHelper';
import type { TreeSelectProps } from 'ant-design-vue';
import { useI18n } from '/@/hooks/web/useI18n';
const { t } = useI18n();
const router = useRouter()
const userStore = useUserStore();
const treeExpandedKeys = ref<string[]>([])
const { createMessage, notification } = useMessage();
const props = defineProps({
  title: { type: String, default: '切换租户' },
  closable: { type: Boolean, default: false },
  username: { type: String, default: '' },
});

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 },
};

const config = {
  maskClosable: false,
  closable: false,
  canFullscreen: false,
  width: '500px',
  minHeight: 20,
  maxHeight: 20,
};
const currTitle = ref('');

const isMultiTenant = ref(false);
const currentTenantName = ref('');
const tenantSelected = ref();
const tenantList = ref<any>([]);
const validate_status = ref('');


// 弹窗显隐
const open = ref(false);
/**
 * 弹窗打开前处理
 */
async function show() {
  // 加载租户
  await loadTenantList();
  // 标题配置
  currTitle.value =
      unref(currentTenantName) && unref(currentTenantName).length > 0 ? `当前租户 :${unref(currentTenantName)}` : props.title;
  open.value = true
}

onMounted(async () => {

})
/**
 *加载租户信息
 */
async function loadTenantList() {
  treeExpandedKeys.value = []
  const result = await listTenantTree();
  if (!result || result.length == 0) {
    return;
  }
  const histroyTenantId : string = userStore.getSelectTenant?.id || ''
  const flatResult : any =  []
  flatten(result, flatResult)
  const useResult = flatResult.filter((item) => item.status === '1');
  let currentTenant = useResult.filter((item) => item.id == histroyTenantId);
  console.log("histroyTenantId", histroyTenantId, currentTenant);
  const tenant = currentTenant && currentTenant.length > 0 ? currentTenant[0] : useResult.length > 0 ? useResult[0] : {};
  currentTenantName.value = tenant.name
  tenantList.value = result;
  tenantSelected.value = tenant.id;
  isMultiTenant.value = true;

  // 设置展开的树节点, 判断是否为主租户
  if (tenant.mainTenantId !== tenant.id) {
    treeExpandedKeys.value = [tenant.id]
  }
}


const heandleTenantChange = async (tenantId) => {
  console.log("change-tenantId", tenantId);
}


/**
 * 提交数据
 */
async function handleSubmit() {
  createMessage.loading({
    content: t('sys.app.tenantSwitchLoading'),
    key: 'tenant_switch_loading'
  });
  try {
    userStore.setLastRoutePath(router.currentRoute.value.fullPath)
    if (unref(isMultiTenant) && !unref(tenantSelected)) {
      validate_status.value = 'error';
      return false;
    }
    const tenantId = unref(tenantSelected)
    await userStore.switchTenant(tenantId)
    close()
    // TODO appId先写死
    await router.push({ path: "/", query: { tenantId, appId: '1' }, replace: true })
    resetRouter()
    location.reload()
  } catch(e) {
    console.error(e);
    // createMessage.error('切换失败')
  } finally {
    createMessage.destroy('tenant_switch_loading');
  }


}

/**
 * 关闭model
 */
function close() {
  currTitle.value = '';

  isMultiTenant.value = false;
  currentTenantName.value = '';
  tenantSelected.value = '';
  tenantList.value = [];
  validate_status.value = '';
  open.value = false;
}

defineExpose({
  show,
});
</script>
<style lang="less" scoped>
.loginSelectForm {
  margin-bottom: -20px;
}

.loginSelectModal {
  top: 20px;
}

.valid-error .ant-select-selection__placeholder {
  color: #f5222d;
}
:deep(.select-tenant-item) {
  display: flex;
  width: 100% !important;
  justify-content: space-between;

}
:deep(.select-tenant-item .title) {
  font-size: 14px;
}

</style>
